<template>
  <div v-if="imgPreview" id="imagePreview" ref="imagePreview" style="z-index: 2020;" @click.stop="hidden">
    <img v-real-img="imgPreview" v-drap-move style="transition: all .3 ease;" class="preview" @click="clickStop" @dblclick="dblclickImg" @mousewheel.prevent="rollImg">
  </div>
</template>

<script>

/**
 * @script CMS 图片预览
 *
 * @Author: yuyuepeng001
 * @Date: 2019-12-21 16:48:17
 *
 */
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      rev: true
    }
  },
  computed: {
    ...mapGetters(['imgPreview'])
  },
  watch: {
    imgPreview: {
      handler: function(val) {
        const Dom = window.document.documentElement.querySelector('#app')
        Dom.style.overflowY = val ? 'hidden' : 'auto'
        this.handlerW()
      }
    }
  },
  methods: {
    handlerW() {
      setTimeout(() => {
        // const bodyW = window.document.body.clientWidth
        const img = window.document.documentElement.querySelector('.preview')
        const imgW = img && img.width
        const imgH = img && img.height
        if (imgW / imgH > 1.2) {
          img && (img.style.width = '80%')
          this.rev = false
        } else {
          img && (img.style.height = '80%')
          this.rev = true
        }
      }, 0)
    },
    clickStop() {
      event.stopPropagation()
    },
    // 双击
    dblclickImg(e) {
      const dom = e.target
      const z = parseInt(this.rev ? dom.style.height : dom.style.width)
      if (z !== 80) {
        dom.style.left = '50%'
        dom.style.top = '50%'
        // dom.style.height = '80%'
        this.reVal(dom, '80%')
        return
      }
      // this.rev ? dom.style.height = `150%` : dom.style.width = `150%`
      this.reVal(dom, '150%')
    },
    /**
     * 判定赋值
     */
    reVal(dom, val) {
      this.rev ? dom.style.height = val : dom.style.width = val
    },
    /**
     * 关闭预览
     */
    hidden() {
      // 清空地址
      // this.$emit('update:src', '')
      this.$store.dispatch('app/updateSrc', '')
    },
    /**
     * 滚轮放大图片
     */
    rollImg(e) {
      const dom = e.target
      let z = parseInt(this.rev ? dom.style.height : dom.style.width)
      z += event.wheelDelta / 12
      if (z >= 30) {
        // this.rev ? dom.style.height = z + '%' : dom.style.width = z + '%'
        this.reVal(dom, z + '%')
      }
    }
  }
}
</script>

<style lang="scss">
  #imagePreview {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: auto;
    margin: 0;
    background-color: #292929c4;
    & .preview {
      position: absolute;
      top: 50%;
      left: 50%;
      cursor: pointer;
      transition-property:width,height;
      transition-duration:.2s;

      /* Safari */
      -webkit-transition-property:width,height;
      -webkit-transition-duration:.2s;
      transform: translate(-50%, -50%);
    }
  }
</style>
